<template>
  <div class="bottom-nav">
    <el-button class="nav-button" @click="goToMessages">
      消息
      <span v-if="totalNotifications > 0" class="notification-badge">
        {{ totalNotifications }}
      </span>
    </el-button>
    <el-button class="nav-button" @click="goToFriends">通讯录</el-button>
    <el-button class="nav-button" @click="goToProfile">我</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { API_BASE_URL } from '@/config';

const router = useRouter();
const totalNotifications = ref(0);
let refreshInterval: number;
const notificationSound = new Audio('/notification.mp3'); // 提示音文件路径

const getTotalNotifications = async () => {
  try {
    const userId = localStorage.getItem('userId');
    const response = await axios.get(`${API_BASE_URL}/users/${userId}/notifications`);
    const previousCount = totalNotifications.value;
    totalNotifications.value = response.data.unreadCount;

    // 如果有新未读消息，播放提示音
    if (totalNotifications.value > previousCount) {
      notificationSound.play();
    }
  } catch (error: any) {
    console.error('获取通知消息失败:', error);
  }
};

const startAutoRefresh = () => {
  refreshInterval = setInterval(getTotalNotifications, 3000); // 每 3 秒刷新一次
};

const stopAutoRefresh = () => {
  clearInterval(refreshInterval);
};

const goToMessages = () => {
  getTotalNotifications(); // 点击时立即刷新
  router.push('/messages');
};

const goToFriends = () => {
  router.push('/friends');
};

const goToProfile = () => {
  router.push('/profile');
};

onMounted(() => {
  getTotalNotifications();
  startAutoRefresh();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<style scoped>
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: white;
  border-top: 1px solid #eee;
  padding: 10px 0;
}

.nav-button {
  flex: 1;
  border: none;
  border-radius: 0;
  padding: 10px;
  position: relative;
}

.notification-badge {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8em;
}
</style> 